package dao

import (
	"github.com/jmoiron/sqlx"
	"go-learn/global"
	demo2 "go-learn/model/pb"
	"go-learn/model/request"
	"strconv"
)

/*
	插入
*/
func Insert(user demo2.User) error {
	sql := "insert into user(name,age) values(?,?)"
	_, err := global.GvaMysql.Exec(sql, user.Name, user.Age)
	return err
}

/*
	批量插入
*/
func InsertAll(users []demo2.User) error {
	sql := "insert into user(name,age) values"
	var datas []interface{}
	for i, user := range users {
		datas = append(datas, user)
		// 根据users长度判断(?)个数，如果不对应sqlx.In()则会报错
		sql += "(?)"
		if i != len(users)-1 {
			sql += ","
		}
	}
	query, args, err := sqlx.In(sql, datas...)
	if err != nil {
		return err
	}
	_, err = global.GvaMysql.Exec(query, args...)
	return err
}

/*
	根据id删除用户
*/
func DeleteUserById(id int64) error {
	sql := "delete from user where id = ?"
	_, err := global.GvaMysql.Exec(sql, id)
	return err
}

/*
	根据id更新用户
*/
func UpdateAgeById(user demo2.User) error {
	sql := "update user set age=? where id=?"
	_, err := global.GvaMysql.Exec(sql, user.Age, user.Id)
	return err
}

/*
	根据id查询用户
*/
func SelectUserById(id int64) (demo2.User, error) {
	sql := "select * from user where id = ?"
	var user demo2.User
	err := global.GvaMysql.Get(&user, sql, id)
	return user, err
}

/*
	查询用户列表
*/
func SelectUserPage(query request.UserPageQuery) ([]demo2.User, error) {
	sql := "select * from user where "
	if query.Name != "" {
		sql += "name='" + query.Name + "'"
	}
	if query.Age != 0 {
		if query.Name != "" {
			sql += " and"
		}
		sql += "age=" + strconv.Itoa(int(query.Age))
	}
	if query.Page < 1 {
		query.Page = 1
	}
	if query.Size < 1 {
		// 默认一页5条记录
		query.Size = 5
	}
	offset := strconv.Itoa((query.Page - 1) * query.Size)
	size := strconv.Itoa(query.Size)
	sql += " limit " + offset + "," + size
	var users []demo2.User
	err := global.GvaMysql.Select(&users, sql)
	return users, err
}
